import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {ClientProspectiveProvider} from "../../../providers/client/client-prospective/client-prospective.provider";

import {CallNumber} from '@ionic-native/call-number';
import * as moment from "moment";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {TabsPage} from "../../tabs/tabs";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {ClientListProvider} from "../../../providers/client/client-list/client-list.provider";
import {ClientIndividualProvider} from "../../../providers/client/client-individual/client-individual.provider";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {LoadingService} from "../../../services/common/loading.service";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";

/**
 * 准客户
 */
@IonicPage()
@Component({
    selector: 'page-client-prospective',
    templateUrl: 'client-prospective.html',
    providers: [
        ClientProspectiveProvider,
        CallNumber,
        ClientNoteEditProvider,
        SideMenuService,
        ClientListProvider,
        ClientIndividualProvider,
        CallNumberService
    ]
})
export class ClientProspectivePage extends InfiniteScrollModel{
    public clientProspectiveModels: Array<any>;
    public clientProNumModel:Array<any>=[];
    public clientProPinYinModel:Array<any>=[];
    public searchKeyword: string;
    public clientTotalDes:string;
    @ViewChild(Content) content: Content;
    infiniteScroll = null;
    get clientItemHeight(): string {
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }
    isLoaded :boolean = false;
    isScrolling = false;
    isViewDidLoad = false;
    isArriveBottom = false;
    dataItemSearchWrapper = {
        isSearchWrapper:true
    };
    openRoot=(name, index)=>this.openTab(name, index);

    openMenu(myEvent){
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index){
        this.navCtrl.popToRoot();
        this.tabsPage.openPage({name:name, index:index});
    }

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public clientProspectiveProvider: ClientProspectiveProvider,
                private callNumber: CallNumber,
                private clientNoteEditProvider: ClientNoteEditProvider,
                public toastCtrl: ToastController,
                private sideMenuService:SideMenuService,
                public cProvider:ClientListProvider,
                public tabsPage:TabsPage,
                private callNumberService: CallNumberService,
                public load:LoadingService,
                public changeRef: ChangeDetectorRef,
                public adpActionSheetController:AdpActionSheetController
    ) {
        super();
        this.clientProspectiveModels = [this.dataItemSearchWrapper];
    }

    ionViewDidLoad(){
        this.isViewDidLoad = true;
        this.getClientList(0);
    }

    ionViewDidEnter(){
        if(!this.isViewDidLoad){
            //进入本页面时，如果数据有更新(例如删除，修改等)，则需要重新拉取准客户列表
            const clientUpdated = MessageBushService.getMessage(MessageBushService.keys.prospectiveClientsUpdated);
            if(clientUpdated == '1'){
                MessageBushService.setMessage(MessageBushService.keys.prospectiveClientsUpdated,void 0);
                this.getClientList(0);
            }
        }
        this.isViewDidLoad = false;
    }

    /**
     * 生日日期格式化
     */
    birthdayFormat(date) {
        if (date == null) {
            return ""
        } else {
            return moment(date).format("YYYY/MM/DD");
        }
    }

    /**
     * 回到顶部
     */
    goUp() {
        if(this.isScrolling){
            setTimeout(() => {
                this.goUp();
            },300);
            return;
        }
        this.content.scrollToTop();
    }

    scrollStart(e){
        this.isScrolling = true;
    }
    scrollEnd(e){
        this.isScrolling = false;
    }

    /**
     * 拨打电话
     */
    callClickHandle(item) {
        if(item.mobileList && item.mobileList.length == 1){
            this.callNumberService.makeCall(item.mobileList[0],this.callNumberService.initCustomerNoteLog(item.leadId), false);
        }else if(item.mobileList.length > 1){
            const phoneArray = [];
            item.mobileList.forEach(phoneNum => {
                phoneArray.push({
                    text:phoneNum,
                    handler:() => {
                        this.callClickHandle({mobileList:[phoneNum]});
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();
        }

    }


    /**
     * 获取准客户首页
     */
    getClientList(notLoading, cb = null) {
        this.pageParams.pageNum = 1;
        this.pageParams.pageSize = 1;
        this.isArriveBottom = false;
        this.isLoaded = false;
        const keyWord = this.pageParams.condition.keyword;
        if(notLoading!==1){
            this.load.showLoading();
        }
        this.cProvider.getClientsFromServer(keyWord).subscribe(data => {
            let res = data.leadList;
            this.isLoaded = true;
            if(cb)cb();
            if(!res || !res.length){
                this.clientProspectiveModels = [];
                this.clientTotalDes = '(0)';
                console.log(this.clientTotalDes)
            }else{
                this.clientTotalDes = `(${res.length})`;
                this.clientProspectiveModels = data.leadList;
            }
            if(this.clientProspectiveModels.indexOf(this.dataItemSearchWrapper) == -1){
                this.clientProspectiveModels.unshift(this.dataItemSearchWrapper);
            }
            this.load.dismissLoading();
        },error2 => {
            if(this.clientProspectiveModels.indexOf(this.dataItemSearchWrapper) == -1){
                this.clientProspectiveModels.unshift(this.dataItemSearchWrapper);
            }
            if(cb)cb();
            this.load.dismissLoading();
        });
    }

    filterConditionsShow = true;
    contentTouchEnd(){
        setTimeout(() => {
            this.filterConditionsShow = true;
        },500);
    }

    searchedHandle(searchKeyword){
        this.pageParams.pageNum = 1;
        if(this.infiniteScroll) this.infiniteScroll.enable(true);
        if(searchKeyword){
            this.pageParams.condition.keyword = searchKeyword.trim();
        }else{
            this.pageParams.condition.keyword = '';
        }
        this.getClientList(0);
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }
    /**
     * 返回
     * @param ev
     */
    backButtonClick(ev) {
        ev.preventDefault();
        ev.stopPropagation();
        this.navCtrl && this.navCtrl.pop(null, null);
    }

    // 到客户详情
    goToDetail(clientNum) {
        this.navCtrl.push('ClientDetailPage', {
            clientNum: clientNum,
            leads: true
        })
    }

    scrolling(){
        const dimensions = this.content.getContentDimensions();
        if((!this.clientProspectiveModels || this.clientProspectiveModels.length < 2) && this.isLoaded){
            return;
        }
        const temp1=dimensions.scrollHeight-dimensions.scrollTop-dimensions.contentHeight<100;
        if (temp1 !== this.isArriveBottom) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }
    /**
     * 跳转添加客户页面
     */
    clientAddHandle() {
        this.navCtrl.push('ClientsAddPage');
    }

    /**
     * 获取分页数据
     * @param infiniteScroll
     */
    // getMore(infiniteScroll) {
    //     this.infiniteScroll = infiniteScroll;
    //     const totalPage = Math.ceil(this.pageInfo.total / this.pageInfo.pageSize);
    //     if (this.pageParams.pageNum < totalPage) {
    //         this.pageParams.pageNum = this.pageInfo.pageNum + 1;
    //         // infiniteScroll.waitFor(this.getNextPageData());
    //     } else {
    //         this.isArriveBottom = true;
    //         infiniteScroll.complete();
    //     }
    // }



    /**
     * 下拉刷新
     * @param refresher
     */
    doRefresh(refresher) {
        this.pageParams.pageNum = 1;
        // if(this.infiniteScroll)this.infiniteScroll.enable(true);
        this.getClientList(1, () => {
            refresher.complete()
        });
    }



}
